<template>
    <!--  外框架-->
    <div class="framework1">
        <!--      内框架-->
        <div class="framework2">
            <div class="top-class-table">
                <div class="header">
                    <div style="margin-left: 10px;font-weight: bold">菜单管理->部门菜单</div>
                </div>
                <!--      按钮行-->
                <div class="button_group">
                    <el-input v-model="searchName" placeholder="请输入部门名称"
                        style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px;" class="custom-search"
                        clearable></el-input>
                    <el-button icon="Search" type="primary" @click="getUnitData()">搜索
                    </el-button>
                </div>
                <div style="height: calc(100vh - 134px)">
                    <el-table :data="unitData" :row-style="{ height: '47px' }"
                        style="width: 100%;height:calc(100% - 68px)" :header-cell-style="{ background: '#f4f3f9' }">
                        <el-table-column prop="name" label="部门名称" width="auto" />
                        <el-table-column prop="address" label="地址" :formatter="formatEmptyValue" width="auto" />
                        <el-table-column align="center" label="操作" width="250" v-if="permissionIsShow.edit">
                            <template v-slot="scope">
                                <el-button type="primary" size="small" icon="Edit"
                                    @click="editUnitMenu(scope.row)">编辑菜单</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--        页数导航栏-->
                    <div class="footer">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="currentPage" :page-sizes="[10, 20,]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="total">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
        <!-- 编辑弹窗-->
        <el-dialog :close-on-click-modal="false" title="菜单权限" v-model="editVisible" width="600px" @close="cancelEdit()">
            <div v-loading="editLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)">
                <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
                    <el-form-item label="部门名称" prop="name">
                        <div style="color: #000000;  padding:0px 10px; ">
                            {{ editForm.name }}
                        </div>
                    </el-form-item>
                    <el-form-item label="菜单权限" prop="menuIds">
                        <div>
                            <div v-for="(node, index) in rootNodes" :key="node.id" class="tree-wrapper">
                                <el-tree :ref="el => { if (el) editTreeRefs[index] = el }" :data="[node]" show-checkbox
                                    check-strictly node-key="id" highlight-current :props="defaultProps"
                                    @check-change="handleNodeChecked" />
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
                <div style="text-align: right; margin-top: 20px;">
                    <el-button @click="cancelEdit()">取消</el-button>
                    <el-button type="primary" @click="submitEditForm()">确定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import request from "../../utils/request.js";


export default {
    data() {
        return {
            // 编辑弹窗
            editVisible: false,
            // 搜索条件
            searchName: '', //搜索名字

            unitData: [],
            currentPage: 1, //页码
            pageSize: 10, //页长
            total: 0,  //总表长

            // 菜单相关数据
            menuOperations: [],
            editTreeRefs: [], // 编辑表单的树引用
            defaultProps: {
                children: 'menuDtos',
                label: 'menuName',
                value: 'id'
            },

            // 编辑表单
            editForm: {
                id: '',
                name: '',
                menuIds: [],
            },
            editFormRules: {

            },

            // 加载状态
            editLoading: false, // 编辑弹窗数据加载状态

            // 登录用户信息
            loginUserInfo: {
                id: '',
                responsibleScope: '', //查询范围
                roleLevel: '', //角色等级
                unitId: '', //内设部门ID
                userRole: '', //角色ID
                permissions: [], // 按钮路径（数据库中的path）
            },
            // 按钮权限
            permissionIsShow: {
                edit: false,
            }
        }

    },
    created() {
        const info = JSON.parse(localStorage.getItem("user"));
        this.loginUserInfo = {
            id: Number(info.id),
            responsibleScope: info.responsibleScope,
            roleLevel: Number(info.roleLevel),
            unitId: Number(info.unitId),
            userRole: Number(info.userRole),
            permissions: info.permissions.filter(item => Number(item.menuId) === 25).map(item => item.path),
        }
        this.permissionIsShow = {
            edit: this.loginUserInfo.permissions.includes('unitMenu-edit'),
        }
        this.load()
    },
    computed: {
        // 根节点列表
        rootNodes() {
            return this.menuOperations;
        }
    },
    methods: {
        load() {
            this.getUnitData()
            this.getAllMenuOperations()
        },
        // 格式化空值
        formatEmptyValue(row, column, cellValue) {
            // 为空、undefined、null或空字符串时显示 "-"
            if (cellValue === undefined || cellValue === null || cellValue === '') {
                return '-';
            }
            return cellValue;
        },
        // 获取内设部门数据
        getUnitData() {
            const unitId = this.loginUserInfo.unitId
            // 管委会用户才允许操作单位菜单
            if (unitId !== 1) {
                this.unitData = []
                this.total = 0
                return
            }
            const responsibleScope = this.loginUserInfo.responsibleScope

            if (responsibleScope === '5') {
                request.get('/unit/page', {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        search: this.searchName,
                    }
                }).then(res => {
                    if (res.code === '200') {
                        if (this.loginUserInfo.roleLevel === 1) {
                            this.unitData = res.data.records
                            this.total = res.data.total
                        } else {
                            // 非管理员，不查询管委会数据
                            this.unitData = res.data.records.filter(item => item.id !== 1)
                            this.total = res.data.total
                        }
                    }
                })
            } else if (responsibleScope === '4') {
                // 部分部门用户
                request.get('/unit/responsibleFindUnitPage', {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        search: this.searchName,
                        userId: this.loginUserInfo.id,
                    }
                }).then(res => {
                    if (res.code === '200') {
                        this.unitData = res.data.records
                        this.total = res.data.total
                    }
                })
            } else {
                // 不负责部门用户
                this.unitData = []
                this.total = 0
            }
        },
        // 获取所有菜单
        async getAllMenuOperations() {
            if (this.menuOperations.length === 0) {
                await request.get("/menu/all").then(res => {
                    if (res.code === '200') {
                        this.menuOperations = res.data;
                    }
                })
            }
        },
        // 获取当前单位菜单
        async getUnitMenu(unitId) {
            let menuIds = []
            await request.get("/unit-menu/getUnitMenu", {
                params: {
                    unitId: unitId,
                }
            }).then(res => {
                if (res.code === '200') {
                    menuIds = res.data || []
                }
            })
            return menuIds
        },

        // 编辑处理
        async editUnitMenu(row) {
            this.editLoading = true; // 显示加载状态
            this.editVisible = true;
            this.editForm = {
                id: row.id,
                name: row.name,
                menuIds: [],
            }

            // 获取当前单位菜单
            this.editForm.menuIds = await this.getUnitMenu(row.id)

            this.$nextTick(() => {
                // 设置已选中的菜单
                this.editTreeRefs.forEach(tree => {
                    if (tree) {
                        tree.setCheckedKeys(this.editForm.menuIds);
                    }
                });
            });
            this.editLoading = false; // 隐藏加载状态
        },
        // 提交编辑表单
        submitEditForm() {
            const params = {
                unitId: this.editForm.id,
                menuIds: this.editForm.menuIds,
            }
            this.editVisible = false;
            request.post("/unit-menu/editUnitMenu", params).then(res => {
                if (res.code === '200' && res.data === true) {
                    this.$message({
                        message: '更新成功',
                        type: 'success'
                    });

                    this.resetEditForm();
                    this.getUnitData();
                } else {
                    this.$message({
                        message: '更新失败，请联系管理员',
                        type: 'error'
                    });
                    this.resetEditForm();
                    this.getUnitData();
                }
            })
        },
        // 取消编辑
        cancelEdit() {
            this.editVisible = false;
            this.resetEditForm();
        },
        // 重置编辑表单
        resetEditForm() {
            if (this.$refs.editFormRef) {
                this.$refs.editFormRef.resetFields();
            }
        },
        // 分页处理
        handleSizeChange(val) {
            this.pageSize = val;
            this.getUnitData();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getUnitData();
        },

        // 处理节点选中事件
        handleNodeChecked(data, checked) {
            // 参数：传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中
            if (checked) {
                // 如果数组里有，就不添加了
                if (this.editForm.menuIds.includes(data.id)) {
                    return;
                } else {
                    this.editForm.menuIds.push(data.id);
                }
            } else {
                // 如果取消选中，从数组中移除
                const index = this.editForm.menuIds.indexOf(data.id);
                if (index !== -1) {
                    this.editForm.menuIds.splice(index, 1);
                }
            }
        },
    }
}
</script>

<style scoped>
#roleSpan {
    color: black;
    text-decoration: none;
}

/*   外框架   */
.framework1 {
    height: calc(100vh - 88px);
    width: calc(100vh - 200px);
    margin-left: 8px;
    border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
    height: calc(100vh - 92px);
    border: solid 1px #D3D3D3;
}

/*   表格大标题   */
.header {
    font-size: 16px;
    font-weight: bold;
    padding: 4px 20px;
    background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
    display: flex;
    padding: 4px 10px;
    background-color: #DDDDDD;
}

/*   表格分页处   */
.footer {
    padding: 4px 10px;
    background-color: #f4f3f9;
}

.el-dialog-image {
    height: 100px;
    width: 200px;
    margin-top: 10px;
    margin-right: 10px;
    border: 1px solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
